package com.roadjava.rbac.security.config;

import com.roadjava.rbac.config.properties.AuthorizationProperties;
import com.roadjava.rbac.manager.CacheManager;
import com.roadjava.rbac.security.*;
import com.roadjava.rbac.security.handler.AccessDeniedHandlerImpl;
import com.roadjava.rbac.security.handler.AuthenticationFailureHandlerImpl;
import com.roadjava.rbac.security.handler.AuthenticationSuccessHandlerImpl;
import com.roadjava.rbac.security.handler.LogoutHandlerImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private static final String SECRET_KEY = "AAAABBBBCCCCDDDD"; // 密钥

    @Resource
    private AuthenticationSuccessHandlerImpl authenticationSuccessHandler;
    @Resource
    private AuthenticationFailureHandlerImpl authenticationFailureHandler;
    @Resource
    private LogoutHandlerImpl logoutHandler;
    @Resource
    private AuthorizationProperties authorizationProperties;
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private AuthenticationEntryPointImpl authenticationEntryPoint;
    @Resource
    private CacheManager cacheManager;
    @Resource
    private AccessDeniedHandlerImpl accessDeniedHandler;
    @Resource
    private LoginAttemptService loginAttemptService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public TokenAuthenticationFilter tokenAuthenticationFilter() {
        return new TokenAuthenticationFilter(cacheManager);
    }

    @Bean
    public DecryptionFilter decryptionFilter() {
        return new DecryptionFilter(SECRET_KEY);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .ignoringAntMatchers("/user/login", "/storage/uploadFile","/user/register",
                        "/user/logout","/favorites/**","/likes/**","/ratings/**",
                        "/suggestions/**","/user/getRolebyUser","/uploads/**","/bannerRes/banners")
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .and()
                .cors().configurationSource(corsConfigurationSource())
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .formLogin()
                .passwordParameter("pwd")
                .loginProcessingUrl("/user/login")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                .and()
                .addFilterBefore(decryptionFilter(), UsernamePasswordAuthenticationFilter.class)
                .addFilterBefore(tokenAuthenticationFilter(), LogoutFilter.class)

                .logout()
                .logoutUrl("/user/logout")
                .addLogoutHandler(logoutHandler)
                .and()
                .authorizeRequests()
                .antMatchers("/websocket/**").permitAll()
                .antMatchers("/user/selectOnlineUser").permitAll()
                .antMatchers("/user/messages/**").permitAll()
                .antMatchers("/uploads/**").permitAll()  // 确保这里明确配置允许访问上传文件
                .antMatchers(authorizationProperties.getWhiteList().toArray(new String[0])).permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**", "/user/register", "/verify/captcha").permitAll()
                .anyRequest().access("@rbacManager.hasPermission(request)")
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);
    }


    private CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8001"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setMaxAge(3600L);
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}


